package duyd.ws.training.xml.handler;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import org.exolab.castor.mapping.GeneralizedFieldHandler;
import org.exolab.castor.mapping.ValidityException;

public class DateTimeFieldHandler extends GeneralizedFieldHandler {

	private static String dateFormatPattern;
	private SimpleDateFormat simpleDateformat;

	public void setConfiguration(Properties config) throws ValidityException {
		dateFormatPattern = config.getProperty("date-format");
	}

	@Override
	public Object convertUponGet(Object value) {
		simpleDateformat = new SimpleDateFormat(dateFormatPattern);
		Date date = (Date) value;
		return simpleDateformat.format(date);
	}

	@Override
	public Object convertUponSet(Object value) {
		String date = (String) value;
		simpleDateformat = new SimpleDateFormat(dateFormatPattern);
		try {
			return simpleDateformat.parse(date);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return value.toString();
		}
	}

	@Override
	public Class<Date> getFieldType() {
		return Date.class;
	}

}
